package cn.com.qtgl.sso.oidc.comp.config;

import cn.com.qtgl.sso.oidc.comp.service.TokenService;
import cn.melonlib.apis.support.comp.config.ApiRequestConfig;
import cn.melonlib.apis.support.comp.config.ApiRequestUserAgent;
import cn.melonlib.objects.maps.JsonMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ConditionalOnProperty(value = "config",prefix = "apis.request",havingValue = "sso",matchIfMissing = false)
public class SsoApiRequestConfig implements ApiRequestConfig {

    @Resource
    private ApiRequestUserAgent apiRequestUserAgent;

    @Resource
    private TokenService tokenService;

    @Value("${system.logs.apis.correlation:true}")
    private boolean correlation=true;

    @Override
    public JsonMap<String> createHeaders() {
        JsonMap<String> headers=defaultHeaders().append(USER_AGENT,apiRequestUserAgent.getUserAgent())
                .append(AUTHORIZATION,"Bearer "+tokenService.getClientToken().getAccessToken())
                ;
        if(correlation){
            headers.append("X-Correlation-ID",tokenService.correlationId());
        }
        String tenant=tokenService.getTenant();
        if(StringUtils.isNotBlank(tenant)){
            headers.append(TENANT,tokenService.getTenant());
        }
        return headers;
    }
}
